package com.demo.java.concurrent.threadpool;

import com.demo.java.utils.ThreadUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ScheduleExecutorTest {
    public static void main(String[] args) {
        // 固定时间间隔, 上一个任务执行时间超过时间间隔则加入等待队列，执行结束立马执行下一个等待任务
        final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            log.info("start: {}", Thread.currentThread().getName());
            ThreadUtils.sleep(3, TimeUnit.SECONDS);
            log.info("sleep end");
        }, 5, 2, TimeUnit.SECONDS);

        // 等待上一个任务结束后延迟固定时间在执行, 上一次任务的结束和当前任务的开始时间间隔固定
        final ScheduledExecutorService scheduledExecutorService1 = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService1.scheduleWithFixedDelay(() -> {
            log.info("start: {}", Thread.currentThread().getName());
            ThreadUtils.sleep(3, TimeUnit.SECONDS);
            log.info("sleep end");
        }, 5, 2, TimeUnit.SECONDS);

        log.info("main. {}", ThreadUtils.threadName());
    }
}
